package ru.aptu.billing_server;

import ru.aptu.billing_message.BasicMessage;
import ru.aptu.billing_message.PaymentRequestMessage;
import ru.aptu.billing_message.RequestMessage;
import ru.aptu.billing_message.ResponseMessage;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: andrey
 * Date: 12/23/11
 * Time: 1:25 AM
 */
public class BillingServer extends SSLServer {

    protected Set<Long> transactions;

    protected final Object monitor;

    public BillingServer(int port, String host) {
        super(host, port);
        transactions = new HashSet<Long>();
        monitor = new Object();
    }

    protected ResponseMessage handleProtocolMessage(RequestMessage message) {
        return new ResponseMessage(message, BasicMessage.Status.OK);
    }

    protected ResponseMessage handleAccountMessage(RequestMessage message) {
        return new ResponseMessage(message, BasicMessage.Status.OK);
    }

    protected ResponseMessage handleTransactionMessage(RequestMessage message) {
        PaymentRequestMessage msg = (PaymentRequestMessage) message;

        synchronized (monitor) {
            if (transactions.contains(msg.getTransaction())) {
                return new ResponseMessage(message, BasicMessage.Status.DUPLICATE_TRN);
            } else {
                transactions.add(msg.getTransaction());
                return new ResponseMessage(message, BasicMessage.Status.OK);
            }
        }
    }

    @Override
    protected ResponseMessage handleRequest(RequestMessage message) {
        switch (message.getType()) {
            case CHECK_PROTOCOL: {
                return handleProtocolMessage(message);
            }
            case CHECK_ACCOUNT: {
                return handleAccountMessage(message);
            }
            case REQUEST_TRANSACTION: {
                return handleTransactionMessage(message);
            }
            default: {
                return badMessage(message);
            }
        }
    }
}
